import React, { Component } from 'react';
import { Button, Toast } from 'antd-mobile';
import router from 'umi/router';
import { connect } from 'dva';
import styles from './index.less';
import MyNavBar from 'components/navbar';
import commonStyles from 'utils/common.less';
import { MyIcon } from 'components/my-icon';
import { ENTER_TYPE, PROCESS_STATUS, AUTHENTICATION_FAIL_CODE, COUNT_DOWN, SERVICE_TYPE, AUTHENTICATION_REULST } from 'utils/Enum'

import { getIsDingTalk, backToOut, dingCloseWindow, closeTheCurrentPage } from 'utils/utils';

@connect(({ AuthenticationModel, pdfModel, sealAndSignatureModel }) => ({ AuthenticationModel, pdfModel, sealAndSignatureModel }))
class AuthenticationSuccess extends Component {
  constructor(props) {
    super(props);
    this.state = {
      message: '认证'
    }
  }
  componentWillUnmount() {
    clearInterval(this.timer)
  }
  componentWillMount() {
    this.getMessage();
  }

  async componentDidMount() {
    //刚开始count复原
    let { dispatch } = this.props
    await dispatch({
      type: 'AuthenticationModel/countDown',
      payload: COUNT_DOWN.RESULT_TIME
    })
    /**
     * 1. 如果是支付宝才需要设置session 当组件加载完成 设置session
     * 2. 判断是哪个请求
     * 3. 如果是支付宝就去请求结果 如果是手机直接开始倒计时
     */
    let { AuthenticationModel: { Certification, session, bizNo, userWsid, returnUrl, enterType, envelopeWsid, participantWsid, haveToAlipay } } = this.props;
    if (bizNo) {
      localStorage.setItem('haveToAlipay', haveToAlipay)
      localStorage.setItem('Contact', bizNo)
      localStorage.setItem("userWsid", userWsid)
      localStorage.setItem("Session", session)
      localStorage.setItem('returnUrl', unescape(returnUrl))
      localStorage.setItem('enterType', enterType)
      localStorage.setItem('bizNo', bizNo)
      localStorage.setItem('Certification', Certification)
      if (envelopeWsid !== '') {
        localStorage.setItem('envelopeWsid', envelopeWsid)
      }
      if (participantWsid !== '') {
        localStorage.setItem('participantWsid', participantWsid)
      }
      Toast.loading('查询中...', 0)

      // 查询中就显示loading动画
      this.getAlipayStatus(bizNo, userWsid, Certification)
    } else {
      this.countDown()
    }
  }

  countDown = async () => {
    //开始倒计时表示查询的结果已经返回 就消除loading动画
    this.timer = setInterval(async () => {
      let { AuthenticationModel: { count }, dispatch } = this.props
      count = count - 1
      if (count < 0) {
        this.goNext()
      } else {
        await dispatch({
          type: 'AuthenticationModel/countDown',
          payload: count
        })
      }
    }, 1000)
  }

  getAlipayStatus = (bizNo, userWsid, Certification) => {
    const { dispatch } = this.props
    switch (Number(Certification)) {
      case PROCESS_STATUS.UNKOWN_PAUTHORIZING_APPLY:
      case PROCESS_STATUS.UNKOWN_EAUTHORIZING_APPLY:
      case PROCESS_STATUS.UNKOWN_EXTERNALPUSR_APPLY:
        dispatch({
          type: "AuthenticationModel/getAlipayDetail",
          payload: {
            userPersonWsid: userWsid,
            bizNo,
            serviceName: SERVICE_TYPE.CONFIRM_AUTH
          },
          callback: () => {
            Toast.hide()
            this.countDown()
          }
        })
        break;
      case PROCESS_STATUS.UNKOWN_WISH_APPLY:
        dispatch({
          type: "AuthenticationModel/getIntendCertificationResult",
          payload: {
            bizNo,
            serviceName: SERVICE_TYPE.CONFIRM_AUTH
          },
          callback: () => {
            Toast.hide()
            this.countDown()
          }
        })
        break;
      default:
        break;
    }

  }

  //页面跳转前先判断需要跳转到哪个
  goNext = () => {
    console.log('进入gonext')
    let authentication = this.getPageInfo();
    clearInterval(this.timer)
    this.selectBack(authentication)
  }

  goBack = (url = '') => {
    console.log('进入goBack')
    localStorage.setItem("nextUrl", url)
    let { AuthenticationModel: { isSuccess, status } } = this.props;
    const isDingTalk = getIsDingTalk()
    console.log(typeof isDingTalk)
    console.log('当前status为：', status)
    console.log('typeOf-status', typeof status)
    console.log(typeof status)
    if (isDingTalk === 'true') {
      //支付宝认证
      if (status === 'undefined' || status === '' || typeof (status) === 'undefined') {
        console.log('当前status为：', status)
        console.log('关闭窗口前的isSuccess', isSuccess)
        console.log('关闭窗口前的nextUrl');
        dingCloseWindow(isSuccess);
        return;
      }
      //手机认证
      // else{
      //   if(url===''||url==='undefined') {
      //     backToOut();
      //   }
      //   else{
      //     router.push(url)
      //   }
      // }
      // return
    }

    if (url === '' || url === 'undefined') {
      //从外部进入就跳转回去
      let returnUrl = localStorage.getItem('returnUrl')
      backToOut();
      return
    }
    localStorage.setItem("nextUrl", '')
    router.push(url)

  }

  /**
   * 选择跳转到哪个路由
   */
  selectBack = (authentication) => {
    console.log('进入selectBack')
    let url = ''
    switch (Number(authentication)) {
      case PROCESS_STATUS.PUSR_AUTHORIZING_SUCCESS://个人手机
      case PROCESS_STATUS.UNKOWN_WISH_SUCCESS://意愿
        this.getFormsAndSubmitConfirm('confirm')
        break;
      case PROCESS_STATUS.UNKOWN_WISH_ERROR:
      case PROCESS_STATUS.PUSR_AUTHORIZING_ERROR:
        // this.pusrGoBack(PROCESS_STATUS.PUSR_AUTHORIZING_ERROR)
        this.goBack('/Signature')
        break;
      case PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS://企业手机
        url = '/RealNameAuthenticationResult?status=' + PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS
        this.goBack(url)
        // router.push({
        //   pathname: '/RealNameAuthenticationResult',
        //   query: {
        //     status:PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS
        //   }
        // })
        break;
      case PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR:
        url = '/RealNameAuthenticationResult?status=' + PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR
        this.goBack(url)
        // router.push({
        //   pathname: '/RealNameAuthenticationResult',
        //   query: {
        //     status: PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR
        //   }
        // })
        break;
      case PROCESS_STATUS.EXPUSR_AUTHORIZING_SUCCESS:
      case PROCESS_STATUS.EXPUSR_AUTHORIZING_ERROR:
        console.log('进入个人认证结果case')
        this.goBack('')
        break;
      default:
        // this.pusrGoBack(PROCESS_STATUS.PUSR_AUTHORIZING_ERROR)
        break;
    }
  }

  pusrGoBack = () => {
    let enterType = localStorage.getItem('enterType')
    if (enterType === ENTER_TYPE.EXTERNAL) {
      //从外部进入就跳转回去
      let returnUrl = localStorage.getItem('returnUrl')
      backToOut();
      return
    }
    router.push('/Signature')
  }//个人用户返回到签署页

  getMessage = () => {
    let data = this.getPageInfo();
    let { EUSR_SUCCESS_C, PUSR_SUCCESS_C } = AUTHENTICATION_REULST;
    switch (data.authentication) {
      case EUSR_SUCCESS_C:
      case PUSR_SUCCESS_C:
        this.setState({
          message: '意愿认证'
        })
        break;
      default:
        this.setState({
          message: '认证'
        })
        break;
    }
  }

  getPageInfo = () => {
    console.log('进入getPageInfo')
    const { AuthenticationModel: { type, status, bizNo, isSuccess, Certification } } = this.props
    let authentication;
    if (bizNo) {
      authentication = this.getAlipay()
    } else {
      authentication = status
    }
    console.log('authentication为', authentication)
    return authentication
  }

  getAlipay = () => {
    console.log('进入getAlipay')
    const { AuthenticationModel: { type, isSuccess, Certification } } = this.props;
    let alipayStatus = ''
    if (isSuccess) {
      alipayStatus = this.authenticationSuccess()
    } else {
      alipayStatus = this.authenticationError()
    }
    console.log('alipayStatus为', alipayStatus)
    return alipayStatus
  }
  authenticationSuccess = () => {
    console.log('进入authenticationSuccess')
    let alipayStatus = ''
    const { AuthenticationModel: { Certification } } = this.props;
    switch (Number(Certification)) {
      case PROCESS_STATUS.UNKOWN_WISH_APPLY:
        alipayStatus = PROCESS_STATUS.UNKOWN_WISH_SUCCESS
        break;
      case PROCESS_STATUS.UNKOWN_PAUTHORIZING_APPLY:
        alipayStatus = PROCESS_STATUS.PUSR_AUTHORIZING_SUCCESS
        break;
      case PROCESS_STATUS.UNKOWN_EAUTHORIZING_APPLY:
        alipayStatus = PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS
        break;
      case PROCESS_STATUS.UNKOWN_EXTERNALPUSR_APPLY:
        alipayStatus = PROCESS_STATUS.EXPUSR_AUTHORIZING_SUCCESS
        break;
      default:
        break
    }
    console.log('alipayStatus为', alipayStatus)
    return alipayStatus
  }
  authenticationError = () => {
    console.log('进入authenticationError')
    const { AuthenticationModel: { Certification } } = this.props;
    let alipayStatus = ''
    switch (Number(Certification)) {
      case PROCESS_STATUS.UNKOWN_WISH_APPLY:
        alipayStatus = PROCESS_STATUS.UNKOWN_WISH_ERROR
        break;
      case PROCESS_STATUS.UNKOWN_PAUTHORIZING_APPLY:
        alipayStatus = PROCESS_STATUS.PUSR_AUTHORIZING_ERROR
        break;
      case PROCESS_STATUS.UNKOWN_EAUTHORIZING_APPLY:
        alipayStatus = PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR
        break;
      case PROCESS_STATUS.UNKOWN_EXTERNALPUSR_APPLY:
        alipayStatus = PROCESS_STATUS.EXPUSR_AUTHORIZING_ERROR
        break;
      default:
        break
    }
    console.log('alipayStatus为', alipayStatus)
    return alipayStatus
  }

  getFormsAndSubmitConfirm = (type) => {//意愿认证成功后请求签署确认并跳转成功页面
    const { dispatch } = this.props;
    const envelopeWsid = localStorage.getItem('envelopeWsid');
    let participantWsid = localStorage.getItem('participantWsid');//参与签署方分配的ID
    let url = ''
    dispatch({
      type: 'sealAndSignatureModel/getFormsSearch',
      payload: {
        envelopeWsid: envelopeWsid,
        participantWsid: participantWsid,
        query: {
          fields: null,
          filters: null,
          sorts: null,
          offset: 0,
          limit: 1000,
        },
      },
      callback: (res) => {
        if (res.length !== 0) {//获取当前的表单数据不为空
          const { dispatch } = this.props;
          const envelopeWsid = localStorage.getItem('envelopeWsid');
          let participantWsid = localStorage.getItem('participantWsid');//参与签署方分配的ID
          let signFormsWsid = [];
          res.forEach((item) => {
            signFormsWsid.push({
              formWsid: item.formWsid,
            });
          });
          dispatch({
            type: 'sealAndSignatureModel/submitConfirm',
            payload: {
              envelopeWsid: envelopeWsid,
              participantWsid: participantWsid,
              formsWsidData: {
                signForms: [...signFormsWsid]
              }
            },
            callback: (res) => {
              if (res === 1) {
                if (type === 'confirm') {
                  this.goBack('/SignTheSuccess')
                  // router.push('/SignTheSuccess');
                } else {
                  url = '/SignTheSuccess'
                }
              } else {
                if (type === 'confirm') {

                  this.pusrGoBack()
                } else {
                  url = '/Signature'
                }

              }
            }
          })
        }
        else {//表单数据为空
          //提示：还未添加任何表单，不允许签署
          if (type === 'confirm') {
            // this.pusrGoBack()
            this.goBack('/Signature')
          } else {
            url = '/Signature'
          }
          Toast.fail('还未添加任何表单，不允许签署')
        }
      }
    });
    return url
  }


  //顶部bar返回选项
  // goBack= () => {
  //   let enterType = localStorage.getItem('enterType')
  //   let url=''
  //   if(enterType === ENTER_TYPE.EXTERNAL) {
  //     //从外部进入就跳转回去
  //     let returnUrl = localStorage.getItem('returnUrl')
  //     url= returnUrl
  //     return url
  //   }
  //   //如果是从内部跳转的
  //   const { AuthenticationModel: { type, status, bizNo, isSuccess ,Certification} } = this.props
  //   if(bizNo) {
  //     // let status = ''
  //     if(isSuccess) {
  //       url = this.NavBarSuccess()
  //     } else {
  //       url = this.NavBarError()
  //     }
  //
  //   } else {
  //     url=this.thirdPhoneNav()
  //   }
  //   // url=this.MyNavBar(authentication,result)
  //   return url
  // }

  thirdPhoneNav = () => {
    const { AuthenticationModel: { status } } = this.props;
    let url = ''
    switch (Number(status)) {
      case PROCESS_STATUS.PUSR_AUTHORIZING_SUCCESS:
      case PROCESS_STATUS.PUSR_AUTHORIZING_ERROR:
        url = '/Signature'
        break;
      case PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS:
      case PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR:
        url = '/RealNameAuthenticationResult?status=' + status
        break;
      default:
        url = '/Signature'
        break

    }
  }
  NavBarSuccess = () => {
    let url = ''
    const { AuthenticationModel: { Certification } } = this.props;
    switch (Number(Certification)) {
      case PROCESS_STATUS.UNKOWN_WISH_APPLY:
      case PROCESS_STATUS.UNKOWN_PAUTHORIZING_APPLY:
        url = '/Signature'
        break;
      case PROCESS_STATUS.UNKOWN_EAUTHORIZING_APPLY:
        url = '/RealNameAuthenticationResult?status=' + PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS
        break;
      default:
        break
    }
    return url
  }
  NavBarError = () => {
    const { AuthenticationModel: { Certification } } = this.props;
    let url = ''
    switch (Number(Certification)) {
      case PROCESS_STATUS.UNKOWN_WISH_APPLY:
      case PROCESS_STATUS.UNKOWN_PAUTHORIZING_APPLY:
        url = '/Signature'
        break;
      case PROCESS_STATUS.UNKOWN_EAUTHORIZING_APPLY:
        url = '/RealNameAuthenticationResult?status=' + PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR
        break;
      default:
        break
    }
    return url
  }

  // MyNavBar=(authentication,result)=>{
  //   let url=''
  //   switch (authentication,result) {
  //     case AUTHENTICATION_REULST.PUSR_SUCCESS:
  //       url='/Signature?result='+result
  //       break;
  //     case AUTHENTICATION_REULST.PUSR_ERROR:
  //       url='/Signature?result='+result
  //       break;
  //     case AUTHENTICATION_REULST.EUSR_SUCCESS:
  //       url='/RealNameAuthenticationResult?status='+result
  //       break;
  //     case AUTHENTICATION_REULST.EUSR_ERROR:
  //       url='/RealNameAuthenticationResult?status='+result
  //       break;
  //     case AUTHENTICATION_REULST.EUSR_SUCCESS_C:
  //       url='/RealNameAuthenticationResult?status='+result+'&Certification='+CERTIFICATION_TYPE.INTEND_CERTIFICATION
  //       break;
  //     case AUTHENTICATION_REULST.EUSR_ERROR_C:
  //       url='/RealNameAuthenticationResult?status='+result+'&Certification='+CERTIFICATION_TYPE.INTEND_CERTIFICATION
  //
  //       break;
  //     case AUTHENTICATION_REULST.EUSR_SUCCESS_P:
  //       url='/RealNameAuthenticationResult?status='+result+'&Certification='+CERTIFICATION_TYPE.REAL_NAME_AUTHENTICATION
  //       break;
  //     case AUTHENTICATION_REULST.EUSR_ERROR_P:
  //       url='/RealNameAuthenticationResult?status='+result+'&Certification='+CERTIFICATION_TYPE.REAL_NAME_AUTHENTICATION
  //       break;
  //     case AUTHENTICATION_REULST.PUSR_SUCCESS_C://意愿认证
  //       url='/Signature?result='+result//头部返回
  //       break;
  //     case AUTHENTICATION_REULST.PUSR_ERROR_C:
  //       url='/Signature?result='+result
  //       break;
  //     case AUTHENTICATION_REULST.PUSR_SUCCESS_P:
  //
  //       url='/Signature?result='+result
  //       break;
  //     case AUTHENTICATION_REULST.PUSR_ERROR_P:
  //
  //       url='/Signature?result='+result
  //       break;
  //     default:
  //       url='/Signature?result='+result
  //       break;
  //   }
  //   return url
  // }

  getHtml = (isSuccess, status, count) => {
    /**
     * 3个状态
     * 成功 失败 和 loading
     */
    const isDingTalk = getIsDingTalk()
    // const contentContainer=commonStyles.result+' '+commonStyles.headerTop
    const contentContainer = isDingTalk === 'true' ? commonStyles.result : commonStyles.result + ' ' + commonStyles.headerTop
    let { message } = this.state;
    return (
      <div className={contentContainer}>
        <div className={commonStyles.IconImg}>
          {
            status == PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS || status == PROCESS_STATUS.EXPUSR_AUTHORIZING_SUCCESS || isSuccess === true || status == PROCESS_STATUS.PUSR_AUTHORIZING_SUCCESS ?
              <MyIcon type='iconqueren' className={commonStyles.Icon + ' ' + styles.SuccessIcon} />
              :
              <>
                {
                  status == PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR || isSuccess === false || status == PROCESS_STATUS.PUSR_AUTHORIZING_ERROR || status == PROCESS_STATUS.EXPUSR_AUTHORIZING_ERROR ?
                    <MyIcon type='iconClose' className={commonStyles.Icon + ' ' + styles.ErrorIcon} />
                    :
                    null
                }
              </>
          }
        </div>
        {
          status == PROCESS_STATUS.EPUSR_AUTHORIZING_SUCCESS || status == PROCESS_STATUS.EXPUSR_AUTHORIZING_SUCCESS || isSuccess === true || status == PROCESS_STATUS.PUSR_AUTHORIZING_SUCCESS ?
            <>
              <div className={commonStyles.titleSuccess}><span>恭喜您，{message}成功</span></div>
              <div className={commonStyles.titleJump}><span>{count}S后自动跳转…</span></div>
            </>
            :
            <>
              {
                status == PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR || isSuccess === false || status == PROCESS_STATUS.PUSR_AUTHORIZING_ERROR || status == PROCESS_STATUS.EXPUSR_AUTHORIZING_ERROR ?
                  <>
                    <div className={commonStyles.titleSuccess}><span>{message}失败</span></div>
                    <div className={commonStyles.titleJump}><span>姓名和证件号码不匹配         请确认后重新提交</span></div>
                    <div className={commonStyles.titleJump}><span>{count}S后自动跳转…</span></div>
                  </>
                  :
                  null
              }
            </>
        }
      </div>
    )
  }
  render() {
    // const url = this.goBack()
    const { AuthenticationModel: { isSuccess, status, count } } = this.props;
    return (
      <div className={styles.baseLayout}>
        <MyNavBar title={"认证结果"} gobackStatus={true} />
        {
          this.getHtml(isSuccess, status, count)
        }
        <div className={'footerContainer' + ' ' + commonStyles.footerContainer}>
          <Button
            type="primary"
            shape="round"
            onClick={this.goNext}
          >
            返回
          </Button>
        </div>
      </div>
    )
  }
}

export default AuthenticationSuccess;
